<!--
 * @Description: Form
 * @Author: zyj
 * @Date: 2022-06-11 14:55:18
 * @LastEditors: zyj
 * @LastEditTime: 2022-06-11 16:46:42
-->
<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'KForm',
  data() {
    return {}
  },
  provide() {
    return {
      // 将表单实例传递给后代
      form: this
    }
  },
  created() {
    // 缓存需要校验的表单项
    this.fields = []
    this.$on('FormItemAdd', (item) => {
      this.fields.push(item)
    })
  },
  props: {
    model: {
      type: Object,
      required: true
    },
    rules: {
      type: Object,
      default: () => {}
    }
  },
  methods: {
    async validate(callback) {
      console.log(this.fields)

      // 将FormItem数组转换为validate()返回的promise数组
      const tasks = this.fields.map((item) => item.validate())
      console.log(tasks)

      // 获取所有结果统一处理
      const results = await Promise.all(tasks)
      let ret = true
      results.forEach((valid) => {
        if (!valid) {
          ret = false // 只要一个失败就失败
        }
      })
      callback(ret)
    }
  }
}
</script>
<style lang="" scoped>
</style>